<!-- 药品处方医嘱页面 -->
<template>
  <div class="drug-orders-page">
    <div class="page-header">
      <h2>药品处方医嘱</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showPatientSelectDialog">
          <el-icon><UserFilled /></el-icon>
          选择患者
        </el-button>
        <!-- <el-button type="success" @click="openPrescriptionDialog" :disabled="!selectedPatient">
          <el-icon><Plus /></el-icon>
          开具处方
        </el-button> -->
      </div>
    </div>

    <!-- 患者信息 -->
    <el-card v-if="selectedPatient" class="patient-info-card">
      <template #header>
        <span>当前患者信息</span>
      </template>
      <div class="patient-details">
        <p><strong>姓名：</strong>{{ selectedPatient.name }}</p>
        <p><strong>身份证号：</strong>{{ selectedPatient.idCard }}</p>
        <p><strong>住院号：</strong>{{ selectedPatient.hospitalNumber || '暂无' }}</p>
        <p><strong>床位号：</strong>{{ selectedPatient.bedNumber || '暂无' }}</p>
      </div>
    </el-card>

    <!-- 药品处方列表 -->
    <el-card class="prescription-list-card">
      <template #header>
        <span>药品处方列表</span>
      </template>
      
      <el-table 
        :data="prescriptions" 
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无处方数据"
      >
        <el-table-column prop="drugName" label="药品名称" width="180" />
        <el-table-column prop="specification" label="规格" width="120" />
        <el-table-column prop="dosage" label="用量" width="100" />
        <el-table-column prop="frequency" label="用法频次" width="120" />
        <el-table-column prop="days" label="用药天数" width="100" />
        <el-table-column prop="totalAmount" label="总量" width="100" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="createTime" label="开具时间" width="150" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <!-- <el-button type="primary" size="small" @click="editPrescription(scope.row)">
                编辑
              </el-button> -->
              <el-button type="danger" size="small" @click="deletePrescription(scope.row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 患者选择对话框 -->
    <div v-if="patientSelectVisible" class="dialog-overlay" @click="patientSelectVisible = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>选择患者</h3>
          <button class="btn-close" @click="patientSelectVisible = false">×</button>
        </div>
        <div class="dialog-body">
          <div class="search-box">
            <input 
              v-model="patientSearchKeyword" 
              placeholder="搜索患者姓名或身份证号..."
              class="input"
              @keyup.enter="searchPatients"
            />
            <button @click="searchPatients" class="btn">搜索</button>
          </div>
          <div class="patient-list">
            <div 
              v-for="patient in patientList" 
              :key="patient.id"
              class="patient-item"
              @click="selectPatient(patient)"
            >
              <div class="patient-info">
                <div class="patient-name">{{ patient.name }}</div>
                <div class="patient-detail">身份证：{{ patient.identityNumber }}</div>
                <div class="patient-detail">住院号：{{ patient.hospitalNumber || '无' }}</div>
              </div>
            </div>
            <div v-if="patientList.length === 0" class="empty-state">
              <p>暂无患者数据</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 处方开具对话框 -->
    <div v-if="prescriptionDialogVisible" class="dialog-overlay" @click="prescriptionDialogVisible = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>开具处方</h3>
          <button class="btn-close" @click="prescriptionDialogVisible = false">×</button>
        </div>
        <div class="dialog-body">
          <p>处方开具功能开发中...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserFilled, Plus } from '@element-plus/icons-vue'
import eventBus from '@/utils/eventBus'

// 响应式数据
const loading = ref(false)
const selectedPatient = ref(null)
const patientSelectVisible = ref(false)
const prescriptionDialogVisible = ref(false)
const prescriptions = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 患者搜索相关
const patientList = ref([])
const patientSearchKeyword = ref('')

// 显示患者选择对话框
const showPatientSelectDialog = () => {
  patientSelectVisible.value = true
  searchPatients() // 加载患者列表
}

// 搜索患者
const searchPatients = async () => {
  try {
    const { pageQueryInsuredPerson } = await import('@/api/admission')
    const queryData = {
      pageNum: 1,
      pageSize: 50,
      name: patientSearchKeyword.value.trim() || undefined
    }
    
    const response = await pageQueryInsuredPerson(queryData)
    if (response.flag && response.data) {
      patientList.value = response.data.records || []
      // 转换数据格式
      patientList.value = patientList.value.map(patient => ({
        ...patient,
        identityNumber: patient.idCard,
        hospitalNumber: patient.hospitalNumber || patient.idCard
      }))
    } else {
      patientList.value = []
      ElMessage.error(response.message || '搜索患者失败')
    }
  } catch (error) {
    console.error('搜索患者失败:', error)
    ElMessage.error('搜索患者失败')
  }
}

// 选择患者
const selectPatient = (patient) => {
  selectedPatient.value = patient
  patientSelectVisible.value = false
  loadPatientPrescriptions()
  ElMessage.success(`已选择患者：${patient.name}`)
}

// 处理患者选择
const handlePatientSelected = (patient) => {
  selectedPatient.value = patient
  loadPatientPrescriptions()
  ElMessage.success(`已选择患者：${patient.name}`)
}

// 打开处方开具对话框
const openPrescriptionDialog = () => {
  prescriptionDialogVisible.value = true
}

// 处理处方创建成功
const handlePrescriptionCreated = () => {
  loadPatientPrescriptions()
  ElMessage.success('处方开具成功')
}

// 加载患者处方数据
const loadPatientPrescriptions = async () => {
  if (!selectedPatient.value) return
  
  loading.value = true
  try {
    const { getPatientDrugOrders } = await import('@/api/admission')
    const response = await getPatientDrugOrders(selectedPatient.value.patientId)
    
    if (response.flag && response.data) {
      prescriptions.value = response.data.map(order => ({
        ...order,
        drugName: order.drugName || '未知药品',
        specification: order.specification || '无',
        dosage: order.dosage || 0,
        frequency: order.frequency || '每日三次',
        days: order.days || 0,
        totalAmount: order.quantity || 0,
        unit: order.unit || '片',
        createTime: order.orderTime ? new Date(order.orderTime).toLocaleString() : '无'
      }))
      total.value = prescriptions.value.length
    } else {
      prescriptions.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载处方数据失败:', error)
    ElMessage.error('加载处方数据失败')
    prescriptions.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 编辑处方
const editPrescription = (prescription) => {
  ElMessage.info('编辑处方功能开发中')
}

// 删除处方
const deletePrescription = async (prescription) => {
  try {
    await ElMessageBox.confirm('确定要删除这个处方吗？', '确认删除', {
      type: 'warning'
    })
    
    const { deletePatientDrugOrder } = await import('@/api/admission')
    const response = await deletePatientDrugOrder(prescription.orderId)
    
    if (response.flag) {
      ElMessage.success('删除成功')
      loadPatientPrescriptions()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除处方失败:', error)
    }
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  loadPatientPrescriptions()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadPatientPrescriptions()
}

// 组件挂载时执行
onMounted(() => {
  // 监听来自患者选择页面的事件
  eventBus.on('addDrugOrder', handlePatientFromEvent)
})

onUnmounted(() => {
  eventBus.off('addDrugOrder', handlePatientFromEvent)
})

// 处理来自事件总线的患者选择
const handlePatientFromEvent = (patient) => {
  selectedPatient.value = patient
  loadPatientPrescriptions()
  ElMessage.success(`已选择患者：${patient.name}，可以开始开具药品处方医嘱`)
}
</script>

<style scoped>
.drug-orders-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.patient-info-card {
  margin-bottom: 20px;
}

.patient-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.patient-details p {
  margin: 0;
}

.prescription-list-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 8px;
  padding: 0;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
  background: #f5f5f5;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-close:hover {
  color: #999;
}

.dialog-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.search-box {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-box .input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-box .btn {
  padding: 8px 16px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.search-box .btn:hover {
  background: #66b1ff;
}

.patient-list {
  max-height: 400px;
  overflow-y: auto;
}

.patient-item {
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.patient-item:hover {
  background: #f0f9ff;
  border-color: #409eff;
}

.patient-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.patient-name {
  font-weight: bold;
  color: #333;
  font-size: 16px;
}

.patient-detail {
  color: #666;
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state p {
  margin: 0;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}
</style>
